<template>
  <div class="data-statistics v-flex">
    <!-- <div :class="tabshow?'show-tab':'hide-tab'" @mouseenter="showtabs" @mouseleave="hidetabs">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="广州铁路局" name="0" />
        <el-tab-pane v-for="(item,index) in selectSection" :key="index" :label="item.deptName" :name="item.deptCode" />
      </el-tabs>
    </div> -->
    <el-row>
      <el-col v-loading="loading.loading1" :span="8" style="max-width:440px;min-width:300px;position:relative;">
        <p class="col-title"><i class="el-icon-s-data" />缺陷基本信息（{{ checkvalue.deptName }}）</p>
        <div class="v-flex col-div">
          <div class="basic-div">
            <div class="itemrow-item" @click="gettableList({},'累计缺陷')"><p>累计缺陷</p><span>{{ tableList.cumulativeDefects }}</span></div>
            <div class="itemrow-item" @click="gettableList({searchDefectStatus:'4'},'累计销号')"><p>累计销号</p><span>{{ tableList.cumulativeCancelNumber }}</span></div>
            <div class="itemrow-item" @click="gettableList({searchDefectStatus:'0,1,2,3'},'当前缺陷')"><p>当前缺陷</p><span>{{ tableList.currentDetects }}</span></div>
            <div class="itemrow-item" @click="gettableList({searchDefectStatus:'1,2,3'},'处理中')"><p>处理中</p><span>{{ tableList.processingDetects }}</span></div>
          </div>
          <div class="basic-div">
            <div class="itemrow-item" @click="gettableList({gradeCode:1},'一级缺陷')"><p>一级缺陷</p><span>{{ tableList.oneLevelDetects }}</span></div>
            <div class="itemrow-item" @click="gettableList({gradeCode:2},'二级缺陷')"><p>二级缺陷</p><span>{{ tableList.twoLevelDetects }}</span></div>
            <div class="itemrow-item" @click="gettableList({cType:'1C'},'1C缺陷')"><p>1C缺陷</p><span>{{ tableList.C1Detects }}</span></div>
            <div class="itemrow-item" @click="gettableList({cType:'2C'},'2C缺陷')"><p>2C缺陷</p><span>{{ tableList.C2Detects }}</span></div>
          </div>
          <div class="basic-div">
            <div class="itemrow-item" @click="gettableList({cType:'3C'},'3C缺陷')"><p>3C缺陷</p><span>{{ tableList.C3Detects }}</span></div>
            <div class="itemrow-item" @click="gettableList({cType:'4C'},'4C缺陷')"><p>4C缺陷</p><span>{{ tableList.C4Detects }}</span></div>
            <div class="itemrow-item" @click="gettableList({cType:'5C'},'5C缺陷')"><p>5C缺陷</p><span>{{ tableList.C5Detects }}</span></div>
            <div class="itemrow-item" @click="gettableList({cType:'6C'},'6C缺陷')"><p>6C缺陷</p><span>{{ tableList.C6Detects }}</span></div>
          </div>
        </div>
      </el-col>
      <el-col v-loading="loading.loading2">
        <div class="col-title" style="display:flex;">
          <p v-if="yearData" style="flex:1;">
            <i class="el-icon-s-data" />缺陷走势
            （{{ yearData.cumulativeDefects[0].date||'' }}--{{ yearData.cumulativeDefects[11].date||'' }}）</p>
          <p v-else style="flex:1;"><i class="el-icon-s-data" />缺陷走势（近一年）</p>
          <!-- <el-select v-model="checkvalue.deptCode" class="dept-select" clearable placeholder="选择供电段">
            <el-option
              v-for="item in selectSection"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode" />
          </el-select> -->
          <el-dropdown class="dept-select">
            <span class="el-dropdown-link">
              {{ checkvalue.deptName }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in selectSection"
                :key="item.deptCode"
                :style="{color:checkvalue.deptName===item.deptName?'#409eff':''}"
                @click.native="selectClick(item)">{{ item.deptName }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div id="chart-one" class="col-div" />
      </el-col>
    </el-row>
    <el-row>
      <el-col v-loading="loading.loading3">
        <p class="col-title"><i class="el-icon-s-data" />缺陷统计</p>
        <div id="chart-two" class="col-div" />
      </el-col>
      <el-col v-loading="loading.loading4" style="max-width:400px;width:40%;">
        <p class="col-title"><i class="el-icon-s-data" />区站缺陷TOP5</p>
        <div id="chart-five" class="col-div" />
        <!-- <div class="sortList v-flex col-div">
          <div v-for="(item,i) in Top5List" :key="i">
            <p>
              <span class="num" :style="`background:${colorList[i]}`">{{ i+1 }}</span>
              <span class="content" :style="`background:${colorList[i]}`">{{ item.siteName }} <span>{{ item.count }}条</span></span>
            </p>
          </div>
        </div> -->
      </el-col>
    </el-row>
    <el-row>
      <el-col v-loading="loading.loading5" :span="8" style="max-width:460px;min-width:340px;">
        <p class="col-title"><i class="el-icon-s-data" />缺陷分类TOP10</p>
        <div id="chart-three" class="col-div" />
      </el-col>
      <el-col v-loading="loading.loading6">
        <p class="col-title"><i class="el-icon-s-data" />装置缺陷对比</p>
        <div id="chart-four" class="col-div" />
      </el-col>
    </el-row>
    <div v-if="isshowtable" :class="['tableClass',bigTableShow?'bigtable':'']">
      <p class="tableClass-top"><span class="el-icon-close" @click="hidetableList" />{{ params.deptName }} （{{ params.name }}）列表</p>
      <statistics-form :params="params" />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import StatisticsForm from './components/statistics-form'
import { getListSection } from '@/api/cms/detect-data/basic'
import { findDefectsBasicInformation, defectsClassification, defectsTypeContrast, defectsTrend, defectsStatistics, defectsTop5 } from '@/api/cms/data-statistics'
import echarts from 'echarts'
export default {
  name: 'DefectStatistics',
  components: {
    StatisticsForm
  },
  data() {
    return {
      isshowtable: false,
      bigTableShow: false,
      tableData: [],
      checkvalue: {
        deptName: '广州铁路局',
        typeClass: '3', // 缺陷来源  检测
        deptCode: ''
      },
      clickNum: 0, // 有数据得缺陷统计加载太慢，判断接口返回结果使用
      params: {},
      timer: null,
      tabshow: true,
      selectSection: [{ deptName: '广州铁路局', deptCode: '' }],
      loading: {
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        loading5: false,
        loading6: false
      },
      Top5List: [],
      colorList: ['#ff2121', '#ff5100', '#ffa600', '#ffd900', '#fff350'],
      myChart: null,
      myChart2: null,
      myChart3: null,
      myChart4: null,
      myChart5: null,
      tableList: {},
      yearData: null,
      myresize: null
    }
  },
  computed: {
    ...mapGetters(['sidebar'])
  },
  watch: {
    'sidebar.opened': function(val) {
      var that = this
      setTimeout(function() {
        that.myChart.resize()
        that.myChart2.resize()
        that.myChart3.resize()
        that.myChart4.resize()
        that.myChart5.resize()
      }, 500)
    },
    'checkvalue.deptCode': function(val) {
      this.clickNum++
      this.tabClick(val, this.clickNum)
    }
  },
  mounted() {
    var that = this
    this.timer = setTimeout(function() {
      that.tabshow = false
    }, 5000)
    getListSection().then(res => {
      if (res.data) {
        this.selectSection = this.selectSection.concat(res.data)
      }
    })
    this.tabClick()

    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    this.myresize = window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        if (_this.myChart)_this.myChart.resize()
        if (_this.myChart2)_this.myChart2.resize()
        if (_this.myChart3)_this.myChart3.resize()
        if (_this.myChart4)_this.myChart4.resize()
        if (_this.myChart5)_this.myChart5.resize()
      })
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.myresize)
    if (this.myChart) {
      this.myChart.dispose()
      this.myChart = null
    }
    if (this.myChart2) {
      this.myChart2.dispose()
      this.myChart2 = null
    }
    if (this.myChart3) {
      this.myChart3.dispose()
      this.myChart3 = null
    }
    if (this.myChart4) {
      this.myChart4.dispose()
      this.myChart4 = null
    }
    if (this.myChart5) {
      this.myChart5.dispose()
      this.myChart5 = null
    }
  },
  methods: {
    selectClick(item) {
      this.checkvalue.deptName = item.deptName
      this.checkvalue.deptCode = item.deptCode
    },
    hidetableList() {
      this.bigTableShow = false
      var that = this
      setTimeout(function() {
        that.isshowtable = false
      }, 400)
    },
    gettableList(obj, name) {
      this.params = Object.assign({}, this.checkvalue, obj)
      this.params.name = name
      this.isshowtable = true
      var that = this
      setTimeout(function() {
        that.bigTableShow = true
      }, 100)
    },
    // 鼠标移入显示tab
    showtabs() {
      clearInterval(this.timer)
      this.tabshow = true
    },
    // 隐藏tab
    hidetabs() {
      var that = this
      this.timer = setTimeout(function() {
        that.tabshow = false
      }, 3500)
    },
    // tab点击事件
    handleClick(val) {
      this.checkvalue.deptCode = val.name
      this.checkvalue.deptName = val.label
    },
    tabClick(val, num = 0) {
      const obj = {
        deptCode: val || ''
      }
      // 获取table数据
      this.findDefectsBasicInformation(obj)
      // 走势图数据
      this.defectsTrend(obj)
      // 缺陷类型统计
      this.defectsStatistics(obj, num)
      // TOP5 数据获取
      this.defectsTop5(obj)
      // 缺陷装置对比
      this.defectsTypeContrast(obj)
      // 饼图数据
      this.defectsClassification(obj)
    },
    // 获取table数据
    findDefectsBasicInformation(obj) {
      this.loading.loading1 = true
      findDefectsBasicInformation(obj).then(res => {
        this.loading.loading1 = false
        this.tableList = res.data
      }).catch(_ => {
        this.loading.loading1 = false
      })
    },
    // 走势图数据
    defectsTrend(obj) {
      this.loading.loading2 = true
      defectsTrend(obj).then(res => {
        this.loading.loading2 = false
        this.yearData = res.data
        const option = {
          legend: ['累计缺陷', '累计销号'],
          xAxis: [],
          series: [
            {
              name: '累计缺陷',
              type: 'bar',
              label: {
                show: true,
                position: 'top'
              },
              data: []
            },
            {
              name: '累计销号',
              type: 'bar',
              label: {
                show: true,
                position: 'top'
              },
              data: []
            }
          ]
        }
        for (const item of this.yearData.cumulativeDefects) {
          option.xAxis.push(item.date)
          option.series[0].data.push(item.count)
        }
        for (const item of this.yearData.cumulativeCancelNumber) {
          option.series[1].data.push(item.count)
        }
        const chart = echarts.init(document.getElementById('chart-one'), 'light')
        this.myChart = chart
        chart.setOption(this.getecharts(option))
      }).catch(_ => {
        this.loading.loading2 = false
      })
    },
    // 缺陷类型统计
    defectsStatistics(obj, num) {
      this.loading.loading3 = true
      defectsStatistics(obj).then(res => {
        if (this.clickNum !== num) return
        this.loading.loading3 = false
        if (res.data) {
          const option = {
            legend: [{ name: '总缺陷', val: 'allDefects' },
              { name: '一级缺陷', val: 'oneLevelDetects' },
              { name: '二级缺陷', val: 'twoLevelDetects' },
              { name: '已处理', val: 'processedDetects' },
              { name: '遗漏缺陷', val: 'unProcessedDetects' }],
            xAxis: Object.keys(res.data),
            series: []
          }
          for (const child of option.legend) {
            const obj = {
              name: child.name,
              type: 'bar',
              label: {
                show: true,
                position: 'top'
              },
              data: []
            }
            for (const item of option.xAxis) {
              obj.data.push(res.data[item][child.val])
            }
            option.series.push(obj)
          }

          const chart = echarts.init(document.getElementById('chart-two'), 'light')
          this.myChart2 = chart
          chart.setOption(this.getecharts(option))
        }
      }).catch(_ => {
        this.loading.loading3 = false
      })
    },
    // TOP5 数据获取
    defectsTop5(obj) {
      this.loading.loading4 = true
      defectsTop5(obj).then(res => {
        this.loading.loading4 = false
        this.Top5List = res.data
        if (res.data) {
          const data = res.data.reverse()
          const option = {
            xAxis: [],
            series: [{
              type: 'bar',
              label: {
                show: true,
                position: 'right'
              },
              data: []
            }]
          }
          for (const item of data) {
            option.xAxis.push(item.siteName)
            option.series[0].data.push(item.count)
          }
          const chart = echarts.init(document.getElementById('chart-five'), 'light')
          this.myChart5 = chart
          chart.setOption(this.getecharts2(option))
        }
      }).catch(_ => {
        this.loading.loading4 = false
      })
    },
    // 缺陷装置对比
    defectsTypeContrast(obj) {
      this.loading.loading6 = true
      defectsTypeContrast(obj).then(res => {
        this.loading.loading6 = false
        if (res.data) {
          const option = {
            legend: ['累计缺陷', '累计销号'],
            xAxis: [],
            series: [{
              name: '累计缺陷',
              type: 'bar',
              label: {
                show: true,
                position: 'top'
              },
              data: []
            },
            {
              name: '累计销号',
              type: 'bar',
              label: {
                show: true,
                position: 'top'
              },
              data: []
            }]
          }
          for (const item of res.data.cumulativeDefects) {
            option.xAxis.push(item.cType)
            option.series[0].data.push(item.count)

            let istrue = false
            for (const child of res.data.cumulativeCancelNumber) {
              if (child.cType === item.cType) {
                istrue = true
                option.series[1].data.push(child.count)
              }
            }
            if (!istrue) {
              option.series[1].data.push(0)
            }
          }
          const chart = echarts.init(document.getElementById('chart-four'), 'light')
          this.myChart4 = chart
          chart.setOption(this.getecharts(option))
        }
      }).catch(_ => {
        this.loading.loading6 = false
      })
    },
    // 饼图数据
    defectsClassification(obj) {
      this.loading.loading5 = true
      defectsClassification(obj).then(res => {
        this.loading.loading5 = false
        if (res.data) {
          const data = []
          for (const item of res.data) {
            const obj = {
              value: item.count,
              name: item.userDefectTypeName
            }
            data.push(obj)
          }
          this.getecharts3(data)
        }
      }).catch(_ => {
        this.loading.loading5 = false
      })
    },
    getecharts(option) {
      var options = {
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0
        },
        title: {
          show: option.xAxis.length === 0,
          textStyle: {
            color: 'grey',
            fontSize: 18
          },
          text: '暂无数据',
          left: 'center',
          top: 'center'
        },
        legend: {
          data: option.legend,
          bottom: 0
        },
        grid: {
          top: 10,
          left: 50,
          right: 30,
          bottom: 50
        },
        xAxis: {
          type: 'category',
          data: option.xAxis,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            align: 'center',
            margin: 10,
            verticalAlign: 'top',
            interval: 0, // 坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
            rotate: option.xAxis.length > 6 ? 16 : 0 // 调整数值改变倾斜的幅度（范围-90到90）
          }
        },
        yAxis: { type: 'value', splitNumber: 4 },
        series: option.series
      }
      return options
    },
    getecharts2(option) {
      var options = {
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0
        },
        title: {
          show: option.xAxis.length === 0,
          textStyle: {
            color: 'grey',
            fontSize: 18
          },
          text: '暂无数据',
          left: 'center',
          top: 'center'
        },
        legend: {
          data: option.legend,
          bottom: 0
        },
        grid: {
          top: 10,
          left: 90,
          right: 40,
          bottom: 20
        },
        yAxis: {
          type: 'category',
          data: option.xAxis,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            align: 'right',
            margin: 2,
            verticalAlign: 'top',
            interval: 0, // 坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
            rotate: option.xAxis.length > 8 ? 16 : 0 // 调整数值改变倾斜的幅度（范围-90到90）
          }
        },
        xAxis: { show: false },
        series: option.series
      }
      return options
    },
    getecharts3(data) {
      const chart3 = echarts.init(document.getElementById('chart-three'), 'light')
      this.myChart3 = chart3
      chart3.setOption({
        tooltip: {
          trigger: 'item'
        },
        title: {
          show: data.length === 0,
          textStyle: {
            color: 'grey',
            fontSize: 18
          },
          text: '暂无数据',
          left: 'center',
          top: 'center'
        },
        grid: {
          top: 10,
          left: 10,
          right: 10,
          bottom: 20
        },
        series: [
          {
            type: 'pie',
            radius: '65%',
            center: ['50%', '50%'],
            data: data
          }
        ]
      })
    }
  }
}
</script>

<style scoped lang="scss">
.data-statistics{
  background: rgb(212, 212, 212);
  padding: 6px;
  overflow-y: auto;
  .hide-tab{
    padding-top: 6px;
    padding-bottom:8px;
    margin-top: -48px;
    transition: all 0.4s linear;
  }
  .show-tab{
    margin-top: 6px;
    padding-bottom:0;
    transition: all 0.4s linear;
  }
  .el-tabs{

    ::v-deep .el-tabs__header{
      margin: 0;
      .el-tabs__item{
        background: white;
      }
      .el-tabs__item:hover{
        transform: scale(1.04,1.06);
      }
      .is-active{
        background: white;
      }
    }
  }

  .el-row{
    flex: 1;
    display: flex;
    min-height: 250px;
    .el-col{
      background: white;
      .col-div{
        padding: 0 8px;
        height:calc(100% - 42px);
        width:100%;
      }
    }
    .el-col:not(:last-child){
      margin-right: 8px;
    }
  }
  .el-row:not(:last-child){
    padding-bottom: 8px;
  }
}
.col-title{
  height: 34px;
  line-height: 34px;
  padding-left: 10px;
  font-weight: bold;
  text-align: left;
  font-size: 15px;
  margin-bottom: 6px;
  color: white;
  background:linear-gradient(180deg,#409eff,#64b1ff);
  .dept-select{
    margin-right: 16px;
    color: white;
    cursor: pointer;
    // ::v-deep .el-input__inner{
    //   width: 120px;
    //   max-width: 160px;
    //   color: white;
    //   background: none;
    //   border: none;
    //   height: 30px;
    //   line-height: 30px;
    // }
    // ::v-deep .el-input__icon{
    //     color: white;
    //     line-height: 34px;
    //   }
  }
  .dept-select:hover{
      transform: scale(1.04,1.04);
    }
}

.col-table{
  width: 100%;
  text-align: left;
  height: calc(100% - 48px);
  border-collapse: collapse;

  border-spacing: 0;
    td,th{
        font-size: 15px;
        color: black;
        width: 25%;
        border: solid 1px #ccc;
        padding: 6px;
    }
    td{
      text-align: center;
      cursor: pointer;
    }
    td:hover{
      color: white;
      font-weight: bold;
      background: #409eff;
    }
}
.sortList{
  div{
    flex: 1;
    padding:4px 4% 0;
    cursor: pointer;
  }
  p{
    height: 32px;
    line-height: 32px;
    display: flex;
    color: white;
    .num{
      display: inline-block;
      text-align: center;
      height: 30px;
      width: 30px;
      border-radius: 50%;
      box-shadow: 2px 2px 2px rgb(102, 102, 102);
    }
    .content{
      padding: 0 10px;
      font-size: 14px;
      flex: 1;
      display: flex;
      span{
        flex: 1;
        text-align: right;
      }
    }
  }
  div:hover{
    background: #eeeeee;
    p{
      transform: scale(1.04,1.04);
    }
  }
}
.basic-div{
  display: flex;
  margin-bottom: 6px;
  flex: 1;
    .itemrow-item{
        flex: 1;
        margin: 0 2px;
        border-radius: 4px;
        cursor: pointer;
        display: grid;
        text-align: center;
        align-items: center;
        color:white;
        background: linear-gradient(180deg,#51c3fb,#99e3fd);
        p{
          font-size: 14px;
        }
        span{
            font-size: 18px;
        }
    }
    .itemrow-item:nth-child(odd){
      background: linear-gradient(180deg,#939bf8,#d1d4f8);
    }
    .itemrow-item:hover{
      transform: scale(1.06,1.06);
    }
}
.el-icon-s-data{
  margin-right: 10px;
  font-size: 18px;
}
.tableClass{
  position: absolute;
  width: 10px;
  height: 10px;
  top:0;
  left: 0;
  background: white;
  background: rgb(212, 212, 212);
  z-index: 3;
  overflow: hidden;
  transition: all 0.4s linear;
}
.bigtable{
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 2003;
}
.tableClass-top{
  height: 36px;
  line-height: 36px;
  padding-left: 14px;
  font-size: 15px;
  color:#409eff;
  background: white;
  .el-icon-close{
    position: absolute;
    font-size: 24px;
    cursor: pointer;
    color: black;
    right: 14px;
    top: 6px;
  }
}

.p_title{
  font-weight: 550;
  font-size: 20px;
  margin-top: 10px;
  margin-bottom: 8px;
  margin-left: 18px;
}
</style>
